#!/bin/bash

# 语音增强对比平台 - 自动化部署脚本
# 适用于 Ubuntu/Debian Linux服务器

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================"
echo "  语音增强对比平台 - 自动化部署"
echo "========================================${NC}"
echo ""

# 错误处理
set -e
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
trap 'echo -e "${RED}❌ 部署失败于命令: ${last_command}${NC}"; exit 1' ERR

# ============================================
# 步骤1: 检查系统环境
# ============================================
echo -e "${YELLOW}[1/8] 检查系统环境...${NC}"

# 检查操作系统
if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo -e "${GREEN}✅ 操作系统: $NAME $VERSION${NC}"
else
    echo -e "${RED}❌ 无法识别操作系统${NC}"
    exit 1
fi

# 检查是否有sudo权限
if ! sudo -n true 2>/dev/null; then
    echo -e "${YELLOW}⚠️  需要sudo权限，请输入密码${NC}"
    sudo -v
fi

echo ""

# ============================================
# 步骤2: 安装Node.js
# ============================================
echo -e "${YELLOW}[2/8] 安装Node.js...${NC}"

if ! command -v node &> /dev/null; then
    echo "正在安装Node.js 18.x..."
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt-get install -y nodejs
    echo -e "${GREEN}✅ Node.js安装完成${NC}"
else
    echo -e "${GREEN}✅ Node.js已安装: $(node -v)${NC}"
fi

echo -e "${GREEN}✅ npm版本: $(npm -v)${NC}"
echo ""

# ============================================
# 步骤3: 安装Git
# ============================================
echo -e "${YELLOW}[3/8] 检查Git...${NC}"

if ! command -v git &> /dev/null; then
    echo "正在安装Git..."
    sudo apt-get install -y git
    echo -e "${GREEN}✅ Git安装完成${NC}"
else
    echo -e "${GREEN}✅ Git已安装: $(git --version)${NC}"
fi

echo ""

# ============================================
# 步骤4: 安装项目依赖
# ============================================
echo -e "${YELLOW}[4/8] 安装项目依赖...${NC}"

# 检查是否在项目目录
if [ ! -f "package.json" ]; then
    echo -e "${RED}❌ 未找到package.json，请在项目根目录运行此脚本${NC}"
    exit 1
fi

# 安装依赖
npm install

echo -e "${GREEN}✅ 依赖安装完成${NC}"
echo ""

# ============================================
# 步骤5: 创建必要目录
# ============================================
echo -e "${YELLOW}[5/8] 创建必要目录...${NC}"

mkdir -p uploads
mkdir -p logs

chmod 755 uploads
chmod 755 logs

echo -e "${GREEN}✅ 目录创建完成${NC}"
echo -e "   - uploads/ (上传目录)"
echo -e "   - logs/ (日志目录)"
echo ""

# ============================================
# 步骤6: 构建前端
# ============================================
echo -e "${YELLOW}[6/8] 构建前端资源...${NC}"

npm run build

echo -e "${GREEN}✅ 前端构建完成: dist/${NC}"
echo ""

# ============================================
# 步骤7: 安装和配置PM2
# ============================================
echo -e "${YELLOW}[7/8] 安装PM2进程管理器...${NC}"

if ! command -v pm2 &> /dev/null; then
    echo "正在安装PM2..."
    sudo npm install -g pm2
    echo -e "${GREEN}✅ PM2安装完成${NC}"
else
    echo -e "${GREEN}✅ PM2已安装: $(pm2 -v)${NC}"
fi

echo ""

# ============================================
# 步骤8: 启动服务
# ============================================
echo -e "${YELLOW}[8/8] 启动服务...${NC}"

# 停止旧进程（如果存在）
pm2 delete voice-community 2>/dev/null || true

# 启动服务
pm2 start server.js --name voice-community --env production

# 保存进程列表
pm2 save

# 设置开机自启（仅在首次部署时需要）
if [ ! -f ~/.pm2/startup.sh ]; then
    echo -e "${YELLOW}配置开机自启动...${NC}"
    pm2 startup | grep "sudo" | bash || true
fi

echo -e "${GREEN}✅ 服务启动成功${NC}"
echo ""

# ============================================
# 显示部署结果
# ============================================
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}🎉 部署完成！${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 显示服务状态
pm2 list

echo ""
echo -e "${BLUE}服务信息:${NC}"
echo -e "  ${GREEN}✅ 后端服务:${NC} http://localhost:3001"
echo -e "  ${GREEN}✅ 前端文件:${NC} dist/ 目录"
echo -e "  ${GREEN}✅ 上传目录:${NC} uploads/"
echo -e "  ${GREEN}✅ 日志目录:${NC} logs/"
echo ""

echo -e "${BLUE}管理命令:${NC}"
echo -e "  ${YELLOW}查看日志:${NC} pm2 logs voice-community"
echo -e "  ${YELLOW}重启服务:${NC} pm2 restart voice-community"
echo -e "  ${YELLOW}停止服务:${NC} pm2 stop voice-community"
echo -e "  ${YELLOW}查看状态:${NC} pm2 status"
echo -e "  ${YELLOW}监控资源:${NC} pm2 monit"
echo ""

echo -e "${BLUE}下一步操作:${NC}"
echo -e "  1️⃣  配置Nginx反向代理（可选）"
echo -e "  2️⃣  配置域名和DNS"
echo -e "  3️⃣  配置SSL证书（Let's Encrypt）"
echo -e "  4️⃣  设置定期备份"
echo ""

echo -e "${BLUE}测试访问:${NC}"
echo -e "  curl http://localhost:3001/api/audio-list"
echo ""

echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}部署脚本执行完成！${NC}"
echo -e "${BLUE}========================================${NC}"

